<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>微加加 - 微信好友批量添加工具</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <style>
    .title-bar {
      background-color: #4CAF50;
      color: white;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0.75rem 1rem;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    .title-text {
      font-size: 1.25rem;
      font-weight: 600;
      letter-spacing: 0.025em;
    }
    .btn {
      padding: 0.5rem 1rem;
      border-radius: 0.375rem;
      transition: all 0.2s;
      outline: none;
    }
    .btn-primary {
      background-color: #007BFF;
      color: white;
    }
    .btn-primary:hover {
      background-color: #0069d9;
    }
    .form-label {
      display: block;
      font-size: 0.875rem;
      font-weight: 500;
      color: #374151;
      margin-bottom: 0.25rem;
    }
    .form-input {
      width: 100%;
      padding: 0.5rem 0.75rem;
      border: 1px solid #d1d5db;
      border-radius: 0.375rem;
      transition: all 0.2s;
    }
    .form-input:focus {
      outline: none;
      border-color: rgba(76, 175, 80, 0.5);
      box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
    }
    .card {
      background-color: white;
      border-radius: 0.5rem;
      box-shadow: 0 1px 2px rgba(0,0,0,0.05);
      padding: 1rem;
    }
    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0,0,0,0.5);
      z-index: 1000;
      align-items: center;
      justify-content: center;
    }
    .modal-content {
      background-color: white;
      border-radius: 0.5rem;
      width: 90%;
      max-width: 600px;
      max-height: 90vh;
      overflow-y: auto;
      padding: 1.5rem;
      animation: modalFadeIn 0.3s;
    }
    @keyframes modalFadeIn {
      from { opacity: 0; transform: translateY(-20px); }
      to { opacity: 1; transform: translateY(0); }
    }
    .schedule-item {
      border-left: 3px solid #4CAF50;
      background-color: #f8f9fa;
      padding: 0.75rem;
      margin-bottom: 0.5rem;
      border-radius: 0 0.375rem 0.375rem 0;
      position: relative;
    }
    .schedule-item-actions {
      position: absolute;
      right: 0.75rem;
      top: 0.75rem;
    }
    .badge {
      display: inline-block;
      padding: 0.25rem 0.5rem;
      font-size: 0.75rem;
      border-radius: 0.25rem;
      background-color: #e5e7eb;
      color: #4b5563;
    }
    .badge-green {
      background-color: #d1fae5;
      color: #065f46;
    }
    .badge-gray {
      background-color: #f3f4f6;
      color: #4b5563;
    }
    .time-conflict {
      border: 1px solid #ef4444;
      box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
    }
  </style>
</head>

<body class="bg-gray-50 min-h-screen">
  <div class="flex flex-col h-screen">
    <!-- 标题栏 -->
    <div class="title-bar">
      <div class="flex items-center space-x-2">
        <i class="fab fa-weixin text-2xl"></i>
        <span class="title-text">微加加 - 微信好友批量添加工具</span>
      </div>
      <div class="flex space-x-2">
        <button class="text-white hover:text-gray-200 p-1" title="最小化">
          <i class="fas fa-window-minimize"></i>
        </button>
        <button class="text-white hover:text-gray-200 p-1" title="最大化">
          <i class="fas fa-window-maximize"></i>
        </button>
        <button class="text-white hover:text-gray-200 p-1" title="关闭" onclick="window.close()">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>

    <div class="flex flex-1 overflow-hidden">
      <!-- 左侧功能区 -->
      <div class="w-56 bg-white shadow-sm border-r border-gray-200 flex-shrink-0">
        <div class="p-3 bg-gray-50 text-xs uppercase text-gray-500 font-semibold">功能菜单</div>
        <div class="py-3 px-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer bg-primary/10 border-l-4 border-primary text-primary font-medium">
          <i class="fas fa-user-plus mr-2"></i>批量添加好友
        </div>
        <div class="py-3 px-4 border-b border-gray-100 opacity-50 cursor-not-allowed">
          <i class="fas fa-comments mr-2"></i>微信群加好友 (开发中)
        </div>
        <div class="py-3 px-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer">
          <i class="fas fa-cog mr-2"></i>系统设置
        </div>
        <div class="py-3 px-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer">
          <i class="fas fa-question-circle mr-2"></i>帮助中心
        </div>
      </div>

      <!-- 右侧操作区 -->
      <div class="flex-1 overflow-y-auto p-4 bg-gray-50">
        <div class="card mb-4">
          <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
            <i class="fas fa-user-plus text-green-600 mr-2"></i>批量添加好友
          </h2>

          <form id="add-friends-form" class="space-y-4">
            <div class="form-group">
              <label for="applyMsg" class="form-label">申请好友信息 <span class="text-xs text-gray-500">(使用 {name} 占位)</span></label>
              <textarea id="applyMsg" class="form-input" rows="3" placeholder="请输入申请信息">您好，我是{name}，想加您为微信好友</textarea>
            </div>
            
            <div class="form-group">
              <label for="prefix" class="form-label">备注前缀</label>
              <input type="text" id="prefix" class="form-input" placeholder="请输入备注前缀" value="21届土木工程">
            </div>
            
            <div class="form-group">
              <label for="excelFile" class="form-label">选择Excel文件</label>
              <div class="flex items-center">
                <input type="file" id="excelFile" class="hidden" accept=".xlsx,.xls">
                <button type="button" id="selectFileBtn" class="btn btn-primary mr-2">
                  <i class="fas fa-file-excel mr-1"></i> 选择文件
                </button>
                <span id="selectedFileName" class="text-sm text-gray-500">未选择文件</span>
              </div>
            </div>
            
            <!-- 定时任务复选框 -->
            <div class="form-group">
              <label class="inline-flex items-center">
                <input type="checkbox" id="enableSchedule" class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                <span class="ml-2 text-sm text-gray-700">设置定时任务</span>
              </label>
            </div>
            
            <!-- 定时任务摘要显示区域 -->
            <div id="scheduleSummary" class="hidden bg-blue-50 border border-blue-100 rounded p-3">
              <div class="flex justify-between items-center mb-2">
                <h4 class="font-medium text-blue-800">
                  <i class="fas fa-clock mr-2"></i>已设置定时任务
                </h4>
                <button type="button" id="manageSchedulesBtn" class="text-blue-600 hover:text-blue-800 text-sm">
                  <i class="fas fa-edit mr-1"></i>管理任务
                </button>
              </div>
              <div id="schedulesCount" class="text-sm text-blue-700">
                共 <span class="font-medium">0</span> 个定时任务
              </div>
            </div>
            
            <div class="form-group">
              <label class="inline-flex items-center">
                <input type="checkbox" class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                <span class="ml-2 text-sm text-gray-700">记住设置内容</span>
              </label>
            </div>
            
            <div class="pt-2">
              <button type="button" id="startBtn" class="btn btn-primary w-full py-3 flex items-center justify-center">
                <i class="fas fa-play mr-2"></i> 开始添加好友
              </button>
            </div>
          </form>
        </div>
        
        <!-- 进度显示区域 -->
        <div class="card">
          <h3 class="text-base font-medium text-gray-700 mb-3">任务进度</h3>
          <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">
            <div id="progressBar" class="bg-green-600 h-2.5 rounded-full" style="width: 0%"></div>
          </div>
          <div class="flex justify-between text-xs text-gray-500">
            <span>0/0 完成</span>
            <span id="progressStatus">准备就绪</span>
          </div>
          <div id="taskLog" class="mt-3 text-sm text-gray-600 h-32 overflow-y-auto bg-gray-50 p-2 rounded">
            <!-- 任务日志将在这里显示 -->
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 定时任务管理弹窗 -->
  <div id="scheduleModal" class="modal">
    <div class="modal-content">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold text-gray-800">
          <i class="fas fa-clock text-green-600 mr-2"></i>定时任务管理
        </h3>
        <button id="closeModalBtn" class="text-gray-400 hover:text-gray-600">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div class="space-y-4">
        <!-- 新增任务表单 -->
        <div class="card">
          <h4 class="font-medium text-gray-700 mb-3">添加新定时任务</h4>
          <div class="grid md:grid-cols-2 gap-4">
            <div class="form-group">
              <label for="modalTaskName" class="form-label">任务名称</label>
              <input type="text" id="modalTaskName" class="form-input" placeholder="例如: 上午添加校友">
            </div>
            
            <div class="form-group">
              <label for="modalTaskDate" class="form-label">开始日期</label>
              <input type="date" id="modalTaskDate" class="form-input">
            </div>
            
            <div class="form-group">
              <label for="modalTaskTime" class="form-label">执行时间</label>
              <input type="time" id="modalTaskTime" class="form-input">
            </div>
            
            <div class="form-group">
              <label for="modalDailyLimit" class="form-label">每日添加上限</label>
              <input type="number" id="modalDailyLimit" class="form-input" placeholder="例如: 20" min="1" max="50" value="20">
            </div>
            
            <div class="form-group">
              <label for="modalRepeatMode" class="form-label">重复模式</label>
              <select id="modalRepeatMode" class="form-input">
                <option value="daily">每天</option>
                <option value="weekdays">工作日(周一至周五)</option>
                <option value="weekends">周末(周六至周日)</option>
                <option value="once">仅一次</option>
              </select>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button type="button" id="addScheduleBtn" class="btn btn-primary">
              <i class="fas fa-plus mr-1"></i> 添加任务
            </button>
          </div>
        </div>
        
        <!-- 任务列表 -->
        <div class="card">
          <h4 class="font-medium text-gray-700 mb-3">已设置的定时任务</h4>
          <div id="schedulesList" class="space-y-3">
            <div class="text-center text-gray-400 py-6" id="noSchedulesHint">
              <i class="fas fa-clock text-2xl mb-2"></i>
              <p>暂无定时任务</p>
              <p class="text-xs mt-1">点击上方"添加任务"按钮创建</p>
            </div>
          </div>
        </div>
        
        <div class="flex justify-end space-x-3 pt-4">
          <button type="button" id="cancelModalBtn" class="btn bg-gray-200 text-gray-700 hover:bg-gray-300">
            关闭
          </button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 存储所有定时任务
    let schedules = [];
    
    // 检查时间是否冲突
    function hasTimeConflict(newDate, newTime, excludeId = null) {
      return schedules.some(schedule => {
        // 排除自身检查
        if (excludeId && schedule.id === excludeId) return false;
        return schedule.date === newDate && schedule.time === newTime;
      });
    }
    
    // 更新时间输入框的冲突状态
    function updateTimeConflictStatus() {
      const dateInput = document.getElementById('modalTaskDate');
      const timeInput = document.getElementById('modalTaskTime');
      
      if (!dateInput || !timeInput) return;
      
      if (hasTimeConflict(dateInput.value, timeInput.value)) {
        timeInput.classList.add('time-conflict');
      } else {
        timeInput.classList.remove('time-conflict');
      }
    }
    
    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
      // 设置日期和时间默认值
      initDefaultDateTime();
      
      // 文件选择按钮事件
      document.getElementById('selectFileBtn').addEventListener('click', function() {
        document.getElementById('excelFile').click();
      });
      
      // 文件选择后显示文件名
      document.getElementById('excelFile').addEventListener('change', function() {
        document.getElementById('selectedFileName').textContent = 
          this.files && this.files[0] ? this.files[0].name : '未选择文件';
      });
      
      // 启用/禁用定时任务
      document.getElementById('enableSchedule').addEventListener('change', function() {
        const summary = document.getElementById('scheduleSummary');
        summary.classList.toggle('hidden', !this.checked);
        
        if (this.checked && schedules.length === 0) {
          openScheduleModal();
        }
        updateScheduleCount();
      });
      
      // 管理定时任务按钮
      document.getElementById('manageSchedulesBtn').addEventListener('click', openScheduleModal);
      
      // 弹窗关闭按钮
      document.getElementById('closeModalBtn').addEventListener('click', closeModal);
      document.getElementById('cancelModalBtn').addEventListener('click', closeModal);
      
      // 添加定时任务按钮
      const addBtn = document.getElementById('addScheduleBtn');
      if (addBtn) {
        addBtn.addEventListener('click', function(e) {
          e.preventDefault();
          addNewSchedule();
        });
      }
      
      // 开始按钮事件
      document.getElementById('startBtn').addEventListener('click', startTask);
      
      // 监听时间输入变化，实时检测冲突
      const dateInput = document.getElementById('modalTaskDate');
      const timeInput = document.getElementById('modalTaskTime');
      if (dateInput) dateInput.addEventListener('change', updateTimeConflictStatus);
      if (timeInput) timeInput.addEventListener('change', updateTimeConflictStatus);
    });
    
    // 初始化日期时间默认值
    function initDefaultDateTime() {
      const today = new Date();
      const tomorrow = new Date(today);
      tomorrow.setDate(tomorrow.getDate() + 1);
      
      // 设置弹窗中的默认值
      const dateInput = document.getElementById('modalTaskDate');
      const timeInput = document.getElementById('modalTaskTime');
      
      if (dateInput) {
        dateInput.min = today.toISOString().split('T')[0];
        dateInput.value = tomorrow.toISOString().split('T')[0];
      }
      
      if (timeInput) {
        // 设置默认时间为下一个整点
        const nextHour = new Date(today);
        nextHour.setHours(nextHour.getHours() + 1, 0, 0, 0);
        const hours = String(nextHour.getHours()).padStart(2, '0');
        const minutes = String(nextHour.getMinutes()).padStart(2, '0');
        timeInput.value = `${hours}:${minutes}`;
      }
      
      // 设置默认任务名称
      const nameInput = document.getElementById('modalTaskName');
      if (nameInput) {
        nameInput.placeholder = "定时任务 " + (schedules.length + 1);
      }
    }
    
    // 打开定时任务管理弹窗
    function openScheduleModal() {
      document.getElementById('scheduleModal').style.display = 'flex';
      updateSchedulesList();
    }
    
    // 关闭弹窗
    function closeModal() {
      document.getElementById('scheduleModal').style.display = 'none';
    }
    
    // 添加新定时任务
    function addNewSchedule() {
      const nameInput = document.getElementById('modalTaskName');
      const dateInput = document.getElementById('modalTaskDate');
      const timeInput = document.getElementById('modalTaskTime');
      const limitInput = document.getElementById('modalDailyLimit');
      const repeatSelect = document.getElementById('modalRepeatMode');
      
      const name = nameInput?.value || `定时任务 ${schedules.length + 1}`;
      const date = dateInput?.value;
      const time = timeInput?.value;
      const limit = limitInput ? parseInt(limitInput.value) : 0;
      const repeat = repeatSelect?.value || 'daily';
      
      // 验证输入
      if (!date) {
        alert('请选择开始日期');
        return;
      }
      
      if (!time) {
        alert('请选择执行时间');
        return;
      }
      
      if (isNaN(limit) || limit <= 0 || limit > 50) {
        alert('请输入有效的每日添加人数 (1-50)');
        return;
      }
      
      // 检查时间冲突
      if (hasTimeConflict(date, time)) {
        alert('该时间点已有定时任务，请选择其他时间');
        return;
      }
      
      // 创建新任务对象
      const newSchedule = {
        id: Date.now(),
        name,
        date,
        time,
        limit,
        repeat,
        enabled: true
      };
      
      // 添加到任务数组
      schedules.push(newSchedule);
      
      // 更新UI
      updateSchedulesList();
      updateScheduleCount();
      
      // 重置表单
      if (nameInput) {
        nameInput.value = '';
        nameInput.placeholder = "定时任务 " + (schedules.length + 1);
      }
      initDefaultDateTime();
      
      // 确保定时任务功能已启用
      const enableCheckbox = document.getElementById('enableSchedule');
      if (enableCheckbox) {
        enableCheckbox.checked = true;
      }
      const summary = document.getElementById('scheduleSummary');
      if (summary) {
        summary.classList.remove('hidden');
      }
    }
    
    // 更新任务列表UI
    function updateSchedulesList() {
      const container = document.getElementById('schedulesList');
      const emptyHint = document.getElementById('noSchedulesHint');
      
      if (!container) return;
      
      container.innerHTML = '';
      
      if (schedules.length === 0) {
        if (emptyHint) emptyHint.style.display = 'block';
        return;
      }
      
      if (emptyHint) emptyHint.style.display = 'none';
      
      schedules.forEach(schedule => {
        const item = document.createElement('div');
        item.className = 'schedule-item';
        item.innerHTML = `
          <div class="schedule-item-actions">
            <button class="text-gray-500 hover:text-red-500 delete-btn mr-2" data-id="${schedule.id}">
              <i class="fas fa-trash-alt"></i>
            </button>
            <button class="text-gray-500 hover:text-blue-500 toggle-btn" data-id="${schedule.id}">
              <i class="fas ${schedule.enabled ? 'fa-toggle-on text-green-500' : 'fa-toggle-off text-gray-400'}"></i>
            </button>
          </div>
          <div class="font-medium">${schedule.name}</div>
          <div class="text-sm text-gray-600 mt-1">
            <span class="mr-3"><i class="far fa-calendar-alt mr-1"></i> ${schedule.date}</span>
            <span class="mr-3"><i class="far fa-clock mr-1"></i> ${schedule.time}</span>
            <span class="mr-3"><i class="fas fa-user-plus mr-1"></i> ${schedule.limit}人/天</span>
          </div>
          <div class="flex items-center mt-2">
            <span class="badge mr-2">
              <i class="fas fa-repeat mr-1"></i> ${getRepeatText(schedule.repeat)}
            </span>
            <span class="badge ${schedule.enabled ? 'badge-green' : 'badge-gray'}">
              ${schedule.enabled ? '已启用' : '已禁用'}
            </span>
          </div>
        `;
        container.appendChild(item);
      });
      
      // 绑定删除按钮事件
      container.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
          const id = parseInt(this.getAttribute('data-id'));
          if (confirm('确定要删除这个定时任务吗？')) {
            schedules = schedules.filter(s => s.id !== id);
            updateSchedulesList();
            updateScheduleCount();
          }
        });
      });
      
      // 绑定切换按钮事件
      container.querySelectorAll('.toggle-btn').forEach(btn => {
        btn.addEventListener('click', function() {
          const id = parseInt(this.getAttribute('data-id'));
          const schedule = schedules.find(s => s.id === id);
          if (schedule) {
            schedule.enabled = !schedule.enabled;
            updateSchedulesList();
            updateScheduleCount();
          }
        });
      });
    }
    
    // 更新任务计数显示
    function updateScheduleCount() {
      const enabledCount = schedules.filter(s => s.enabled).length;
      const countElement = document.getElementById('schedulesCount');
      if (countElement) {
        countElement.innerHTML = 
          `共 <span class="font-medium">${schedules.length}</span> 个定时任务 (${enabledCount}个启用)`;
      }
    }
    
    // 获取重复模式文本
    function getRepeatText(repeatMode) {
      const texts = {
        daily: '每天',
        weekdays: '工作日',
        weekends: '周末',
        once: '仅一次'
      };
      return texts[repeatMode] || repeatMode;
    }
    
    // 开始任务
    function startTask() {
      const applyMsg = document.getElementById('applyMsg')?.value.trim();
      const prefix = document.getElementById('prefix')?.value.trim();
      const excelFile = document.getElementById('excelFile')?.files[0];
      const isScheduled = document.getElementById('enableSchedule')?.checked;
      
      if (!applyMsg) return alert('请输入申请好友信息');
      if (!prefix) return alert('请输入备注前缀');
      if (!excelFile) return alert('请选择Excel文件');
      if (isScheduled && schedules.length === 0) return alert('请至少添加一个定时任务');
      
      if (isScheduled) {
        const enabledSchedules = schedules.filter(s => s.enabled);
        if (enabledSchedules.length === 0) return alert('请启用至少一个定时任务');
        
        alert(`已设置 ${enabledSchedules.length} 个定时任务，系统将按照以下时间自动执行：\n${
          enabledSchedules.map(s => `${s.name} - ${s.date} ${s.time} (每日${s.limit}人)`).join('\n')
        }`);
      } else {
        // 模拟立即执行任务
        simulateTaskExecution();
      }
    }
    
    // 模拟任务执行进度
    function simulateTaskExecution() {
      const progressBar = document.getElementById('progressBar');
      const progressStatus = document.getElementById('progressStatus');
      const taskLog = document.getElementById('taskLog');
      
      if (!progressBar || !progressStatus || !taskLog) return;
      
      progressBar.style.width = '0%';
      progressStatus.textContent = '正在处理...';
      taskLog.innerHTML = '';
      
      let progress = 0;
      const interval = setInterval(() => {
        progress += Math.floor(Math.random() * 5) + 1;
        if (progress > 100) progress = 100;
        progressBar.style.width = `${progress}%`;
        
        if (progress % 20 === 0) {
          const logEntry = document.createElement('div');
          logEntry.textContent = `已处理 ${progress} 条，添加成功 ${Math.floor(progress * 0.9)} 条`;
          taskLog.appendChild(logEntry);
          taskLog.scrollTop = taskLog.scrollHeight;
        }
        
        if (progress >= 100) {
          clearInterval(interval);
          progressStatus.textContent = '任务完成';
          const logEntry = document.createElement('div');
          logEntry.className = 'text-green-600';
          logEntry.textContent = '全部好友申请已发送完成';
          taskLog.appendChild(logEntry);
          taskLog.scrollTop = taskLog.scrollHeight;
        }
      }, 500);
    }
  </script>
</body>
</html>